package site.marqstree.latte.ec.main.cart;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.joanzapata.iconify.widget.IconTextView;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import site.marqstree.latte.core.delegates.bottom.BottomItemDelegate;
import site.marqstree.latte.core.net.RestClient;
import site.marqstree.latte.core.net.callback.ISuccess;
import site.marqstree.latte.core.util.log.LatteLogger;
import site.marqstree.latte.ec.R;
import site.marqstree.latte.ec.R2;
import site.marqstree.latte.ec.pay.FastPay;
import site.marqstree.latte.ec.pay.IAlPayResultListener;
import site.marqstree.latte.ec.profile.AppProfile;
import site.marqstree.latte.ui.recycler.MultipleFields;
import site.marqstree.latte.ui.recycler.MultipleItemEntity;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.ec.main.cart
 * 文件名: ShopCartDelegate
 * 创建者: marqstree
 * 创建时间: 2020/2/1 14:05
 * 描述: TODO
 */
public class ShopCartDelegate extends BottomItemDelegate implements ISuccess,ITotalPriceListener, IAlPayResultListener {

    //购物车数量标记
    private int mCurrentCount = 0;
    private int mTotalCount = 0;

    @BindView(R2.id.tv_shop_cart_total_price)
    TextView mTvTotalPrice;

    @BindView(R2.id.rv_shop_cart)
    RecyclerView mRecyclerView;

    @BindView(R2.id.icon_shop_cart_select_all)
    IconTextView mIconSelectAll = null;

    @OnClick(R2.id.icon_shop_cart_select_all)
    void onClickSelectAll() {
        int listCount = mAdapter.getData().size();
        if(listCount<1)
            return;

        final int tag = (int) mIconSelectAll.getTag();
        int newTag = tag==0?1:0;

        //选中时，字体高亮
        if (newTag == 1) {
            mIconSelectAll.setTextColor
                    (ContextCompat.getColor(getContext(), R.color.app_main));
        }
        //为选中时，灰色字体
        else {
            mIconSelectAll.setTextColor(Color.GRAY);
        }
        //将选中状态存入控件的tag
        mIconSelectAll.setTag(newTag);

        //只更新选中状态发生变化的Item
        //Item只刷新勾选子控件
        // 不采用:mAdapter.notifyDataSetChanged()方法，更新RecyclerView的所有Item，导致RecyclerView发生闪烁
        List<MultipleItemEntity> list = mAdapter.getData();
        int cnt = mAdapter.getItemCount();
        for(int i=0; i<cnt; i++){
            MultipleItemEntity entity = list.get(i);
            boolean isSelected = entity.getField(ShopCartItemFields.IS_SELECTED);
            boolean newSelected = newTag==1;
            if(isSelected!=newSelected) {
                final MultipleItemEntity newEntity = ShopCartItemType.clone(entity);
                newEntity.setField(ShopCartItemFields.IS_SELECTED,newSelected);
                mAdapter.getData().set(i,newEntity);
                //更新指定Item中的指定子控件
                //第二个参数：标识Item中的哪些子控件需要更新
                //ITEM_SELECTED_PAYLOAD：标识只更新RecyclerView的Item中的勾选子控件
                mAdapter.notifyItemChanged(i + mAdapter.getHeaderLayoutCount(), ShopCartAdapter.ITEM_SELECTED_PAYLOAD);
            }
        }
    }

    //删除按钮
    @OnClick(R2.id.tv_top_shop_cart_remove_selected)
    void onClickRemoveSelectedItem() {
        final List<MultipleItemEntity> data = mAdapter.getData();
        //要删除的数据
        final List<MultipleItemEntity> newData = new ArrayList<>();
        for (MultipleItemEntity entity : data) {
            final boolean isSelected = entity.getField(ShopCartItemFields.IS_SELECTED);
            if (!isSelected) {
                newData.add(entity);
            }
        }
        mAdapter.setDiffNewData(newData);
        mAdapter.calTotalPrice(newData);
    }

    //清空按钮
    @OnClick(R2.id.tv_top_shop_cart_clear)
    void onClickClear() {
        mAdapter.getData().clear();
        mAdapter.calTotalPrice();
        mAdapter.setEmptyView(getEmptyDataView());
        mAdapter.notifyDataSetChanged();
    }

    private ShopCartAdapter mAdapter = new ShopCartAdapter(null);

    @Override
    public Object setLayout() {
        return R.layout.delegate_shop_cart;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        //默认全不选
        mIconSelectAll.setTag(0);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initRecyclerView();
        RestClient.builder()
                .url(AppProfile.SHOP_CART_DATA_URL)
                .loader(getContext())
                .success(this)
                .build()
                .get();
    }

    @Override
    public void onSuccess(String response) {
        final ArrayList<MultipleItemEntity> data =
                new ShopCartDataConverter()
                        .setJsonData(response)
                        .convert();
        mAdapter.setNewData(data);
        mAdapter.calTotalPrice();
    }

    //初始化RecyclerView
    private void initRecyclerView() {
        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(manager);

        // 先注册需要点击的子控件id（注意，请不要写在convert方法里）
        mAdapter.addChildClickViewIds(
                //勾选框
                R.id.icon_item_shop_cart,
                //减少按钮
                R.id.icon_item_minus,
                //增加按钮
                R.id.icon_item_plus);
        //设置子控件点击事件
        mAdapter.setOnItemChildClickListener(new ItemChildClickListener());
        mAdapter.setTotalPriceListener(this);

        mRecyclerView.setAdapter(mAdapter);

        //设置更新Item比较回调接口
        mAdapter.setDiffCallback(new ShopCartItemDiffCallback());
    }

    //返回空布局
    private View getEmptyDataView() {
        View notDataView = getLayoutInflater().inflate(R.layout.item_shop_cart_empty_view, mRecyclerView, false);
        return notDataView;
    }

    @Override
    public void onTatalPriceChange(double totalPrice) {
        mTvTotalPrice.setText(totalPrice+"");
    }

    //结算按钮
    @OnClick(R2.id.tv_shop_cart_pay)
    void onClickPay() {
        FastPay.create(this).beginPayDialog();
        createOrder();
    }

    //创建订单，注意，和支付是没有关系的
    private void createOrder() {
        final String orderUrl = "你的生成订单的API";
        final WeakHashMap<String, Object> orderParams = new WeakHashMap<>();
        //加入你的参数
        RestClient.builder()
                .url(orderUrl)
                .loader(getContext())
                .params(orderParams)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        //进行具体的支付
                        LatteLogger.d("ORDER", response);
                        final int orderId = JSON.parseObject(response).getInteger("result");
                        FastPay.create(ShopCartDelegate.this)
                                .setPayResultListener(ShopCartDelegate.this)
                                .setOrderId(orderId)
                                .beginPayDialog();
                    }
                })
                .build()
                .post();

    }

    @Override
    public void onPaySuccess() {

    }

    @Override
    public void onPaying() {

    }

    @Override
    public void onPayFail() {

    }

    @Override
    public void onPayCancel() {

    }

    @Override
    public void onPayConnectError() {

    }
}
